﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace YLBaseCommon.Framework
{
    public class HttpService
    {
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="posturl">URL</param>
        /// <param name="postData">请求数据</param>
        /// <returns></returns>
        public static string HttpGetData(string posturl, string Bearer = "")
        {
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                WebHeaderCollection head = new WebHeaderCollection();
                head.Add("Authorization", "Bearer " + Bearer);
                request.Headers = head;
                request.ContentType = "application/json";
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                //Response.Write(content);
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }


        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="posturl">URL</param>
        /// <param name="postData">请求数据</param>
        /// <returns></returns>
        public static string HttpPostData(string posturl, string postData, string Bearer)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                WebHeaderCollection head = new WebHeaderCollection();
                head.Add("Authorization", "Bearer " + Bearer);
                request.Headers = head;
                request.ContentType = "application/json";
                request.ContentLength = data.Length;

                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                //返回结果网页（html）代码
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }



        /// <summary>
        /// Post请求图片
        /// </summary>
        /// <param name="posturl">URL</param>
        /// <param name="postData">请求数据</param>
        /// <returns></returns>
        public static string HttpPostDataImg(string posturl, string postData, string Bearer)
        {
            Stream outstream = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                WebHeaderCollection head = new WebHeaderCollection();
                head.Add("Authorization", "Bearer " + Bearer);
                request.Headers = head;
                request.ContentType = "image/*";
                request.ContentLength = data.Length;

                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                //返回结果网页（html）代码
                using (Stream stream = response.GetResponseStream())
                {

                    string ioPath = "";
                    string cPath = "wxOpen/";
                    string dirPath = ioPath + cPath;
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    string FileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + ".jpg";
                    var mStream = new MemoryStream();

                    byte[] buffer = new byte[1024];
                    int byteCount;
                    do
                    {
                        byteCount = stream.Read(buffer, 0, buffer.Length);
                        mStream.Write(buffer, 0, byteCount);
                    } while (byteCount > 0);

                    mStream.Seek(0, SeekOrigin.Begin);
                    FileStream fsWrite = new FileStream(dirPath + FileName, FileMode.OpenOrCreate);
                    byte[] mybyte = mStream.ToArray();
                    //3.开始写入
                    fsWrite.Write(mybyte, 0, mybyte.Length);
                    //4.关闭
                    fsWrite.Close();
                    fsWrite.Dispose();
                    string WebResoruceUrl = "";
                    return WebResoruceUrl + cPath + FileName;
                }
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }
    }
}
